<template>
	<div class="tools-warp">
		<el-card shadow="hover">
			<div slot="header">
				<div style="width: 400px; display: flex;align-items: center;">
					<el-input v-model="parms.keyword" placeholder="请输入内容" style="margin-right: 10px;"></el-input><el-button @click="sherchQuer"
						type="primary">查询</el-button> <el-button type="success" @click="addcanpus">添加</el-button>
				</div>
			</div>
			<el-table :data="tableData" stripe style="width: 100%">
				<el-table-column prop="studentName" label="学员姓名" align="center">
				</el-table-column>
				<el-table-column prop="courseName" label="课程名称" align="center">
				</el-table-column>
				<el-table-column prop="courseNum" label="校区名称" align="center">
					<template slot-scope="scope">
						{{ scope.row.courseInfo.campusName }}
					</template>
				</el-table-column>
				<el-table-column label="收费标准(/课时)" align="center">
					<template slot-scope="scope">
						{{ scope.row.courseInfo.standard }}
					</template>
				</el-table-column>
				<el-table-column prop="courseNum" label="购买课时" align="center"></el-table-column>
				<el-table-column prop="amount" label="课时金额" align="center"></el-table-column>
				<el-table-column prop="residueNum" label="剩余课时" align="center">
				</el-table-column>
				<el-table-column prop="createDate" label="创建时间" align="center">
				</el-table-column>
				<el-table-column fixed="right" label="操作" width="300" align="center">
					<template slot-scope="scope">
						<el-button @click="endClick(scope.row)" type="primary" size="small">编辑</el-button>
						<el-button @click="handleClick(scope.row)" type="danger" size="small">删除</el-button>
						<el-button @click="dolodalClick(scope.row)" type="success" size="small">下载合同</el-button>
						<el-button @click="outmoeClick(scope.row)" type="warning" size="small">退费</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div style="padding: 20px 0;">
				<el-pagination background layout="prev, pager, next" :total="total" @current-change="handleCurrentChange">
				</el-pagination>
			</div>
		</el-card>
		<el-dialog :title="texts" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="签约人" prop="signatoryId">
					<!-- <el-input v-model="ruleForm.signatoryName" placeholder="请输入签约人"></el-input> -->
					<el-select v-model="ruleForm.signatoryId" placeholder="请选择授课教练" style="width: 100%;">
						<el-option v-for="(item, index) in useroptions" :key="index" :label="item.nickName"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<!-- <el-form-item label="纸质编号" prop="paperNumber">
					<el-input v-model="ruleForm.paperNumber" placeholder="请输入纸质编号"></el-input>
				</el-form-item> -->
				<el-form-item label="学员" prop="studentId">
					<el-select v-model="ruleForm.studentId" placeholder="请选择学员" filterable style="width: 100%;">
						<el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="课程" prop="courseId">
					<el-select v-model="ruleForm.courseId" placeholder="请选择课程" style="width: 100%;" @change="changes">
						<el-option v-for="item in opsaqtions" :key="item.value" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="购买课时" prop="courseNum">
					<el-input v-model="ruleForm.courseNum" placeholder="请输入购买课时"> <template slot="append">课时（{{ standard
					}}/课时）</template></el-input>
				</el-form-item>
				<el-form-item label="合同pdf文件">
					<el-upload class="upload-demo" action="https://www.fbty.tech/api/api/accessory/uploadpdf"
						:on-success="handleSuccess" multiple :headers="headers" :before-upload="beforeAvatarUpload"
						:limit="3" :file-list="fileList">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传PDF文件，且不超过5MB</div>
					</el-upload>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="resetForm('ruleForm')">取 消</el-button>
				<el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
			</span>
		</el-dialog>
		<el-dialog title="合同打印" :visible.sync="pdfVisible" width="60%" >
			<div ref="IMG" style="padding: 30px;" >
				<div v-if="objall.length > 0">合同编号: {{objall[0].paperNumber}}</div>
				<div style="padding: 20px 0;">学员信息</div>
				<el-table :data="objall" stripe style="width: 100%" border>
					<el-table-column prop="studentName" label="学生姓名" align="center">
					</el-table-column>
					<el-table-column prop="parentName" label="家长姓名" align="center">
						<template slot-scope="scope">
							<span>{{scope.row.parentName?scope.row.parentName:'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column label="联系电话" prop="phone" align="center"></el-table-column>
					<el-table-column prop="signatoryName" label="签约人" align="center"></el-table-column>
					<el-table-column prop="campusName" label="签约校区" align="center"></el-table-column>
					<el-table-column prop="signatoryTime" label="合同签约日期" align="center">
					</el-table-column>
				</el-table>
				<div style="padding: 20px 0;">课程明细(单位:元)</div>
				<el-table :data="objall" stripe style="width: 100%" border>
					<el-table-column  label="类型" align="center">
						<template slot-scope="scope">
							<span>班课</span>
						</template>
					</el-table-column>
					<el-table-column prop="courseName" label="课程名称/科目" align="center">
					</el-table-column>
					<el-table-column prop="unitPrice" label="单价" align="center"></el-table-column>
					<el-table-column prop="courseNum" label="课时" align="center"></el-table-column>
					<el-table-column prop="amount" label="课程总额" align="center"></el-table-column>
					<el-table-column  label="优惠方案" align="center">
						<template slot-scope="scope">
							<span>-</span>
						</template>
					</el-table-column>
					<el-table-column  label="优惠金额" align="center">
						<template slot-scope="scope">
							<span>-</span>
						</template>
					</el-table-column>
					<el-table-column  label="赠送课时" align="center">
						<template slot-scope="scope">
							<span>-</span>
						</template>
					</el-table-column>
					<el-table-column  label="优惠分摊" align="center">
						<template slot-scope="scope">
							<span>-</span>
						</template>
					</el-table-column>
					<el-table-column prop="amount" label="应收金额" align="center">
						<!-- <template slot-scope="scope">
							<span>-</span>
						</template> -->
					</el-table-column>
				</el-table>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="pdfVisible = false">取 消</el-button>
				<el-button type="primary" @click="okpdfs">下 载</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import { allAdminApi } from '@/api/allapi';
import { Session } from '@/utils/storage';
import fileDownload from "js-file-download";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
const adminApi = allAdminApi();
export default {
	name: 'campus',
	data() {

		return {
			imageUrl: '',
			input: "",
			texts: '添加购买信息',
			dialogVisible: false,
			pdfVisible: false,
			options: [],
			opsaqtions: [],
			tableData: [],
			total: 0,
			standard: 0,
			useroptions: [],
			miniparms: {
				keyword: "",
			},
			formparms: {
				keyword: "",
			},
			parms: {
				limit: 10,
				page: 1,
				keyword: "",
				// roleId:2,
			},
			usersparms: {
				limit: 3000,
				page: 1,
				keyword: "",
				roleId: 2,
			},
			ruleForm: {
				// paperNumber: '',
				signatoryId: '',
				courseId: '',
				courseNum: '',
				studentId: '',
				contractPath: '',
			},
			rules: {
				// paperNumber: [
				// 	{ required: true, message: '请输入纸质编号', trigger: 'change' },
				// ],
				signatoryId: [
					{ required: true, message: '请输入签约人', trigger: 'change' },
				],
				courseNum: [
					{ required: true, message: '请输入购买课时', trigger: 'change' },
				],
				courseId: [
					{ required: true, message: '请选择课程', trigger: 'change' },
				],
				studentId: [
					{ required: true, message: '请选择校区', trigger: 'change' },
				],
			},
			fileList: [],
			headers: { Authorization: 'bearer ' + `${Session.get('token')}` },
			objall: [],
		};
	},
	mounted() {
		this.campusListApi();
		this.casdsListApi();
		this.sherchList()
		this.usersListApis()
	},
	methods: {
		usersListApis() {
			adminApi.userslistApi(this.usersparms).then((res) => {
				if (res.code == 200) {
					this.useroptions = res.result;
				}
			})
		},
		handleSuccess(res) {
			console.log(res.result.path);
			this.ruleForm.contractPath = res.result.path
		},
		beforeAvatarUpload(file) {
			const isJPG = file.type === 'application/pdf';
			const isLt2M = file.size / 1024 / 1024 < 5;

			if (!isJPG) {
				this.$message.error('文件只能是 PDF 格式!');
			}
			if (!isLt2M) {
				this.$message.error('文件大小不能超过 5MB!');
			}
			return isJPG && isLt2M;
		},
		changes(e) {
			this.opsaqtions.forEach((item) => {
				if (item.id === e) {
					this.standard = item.standard
				}
			});

		},
		campusListApi() {
			adminApi.listNotPageList(this.formparms).then((res) => {
				if (res.code == 200) {
					this.options = res.result;
				}
			})
		},
		casdsListApi() {
			adminApi.courseinfofoList(this.miniparms).then((res) => {
				if (res.code == 200) {
					this.opsaqtions = res.result;
				}
			})
		},
		sherchQuer() {
			this.parms.page = 1
			this.sherchList()
		},
		handleCurrentChange(val) {
			this.parms.page = val
			this.sherchList()
		},
		sherchList() {
			adminApi.studentcourseList(this.parms).then((res) => {
				if (res.code == 200) {
					this.tableData = res.result;
					this.total = res.count;
				}
			})
		},
		endClick(row) {
			this.texts = "编辑购买信息";
			this.standard = row.courseInfo.standard
			this.ruleForm = row
			this.dialogVisible = true;
		},
		dolodalClick(row) {//下载合同 
			this.objall = [];
			adminApi.getContractApi(row.id).then((res) => {
				this.objall.push(res.result)
				this.pdfVisible = true;
				})
		},
		handleClick(row) {
			this.$confirm('此操作将永久删除该课程, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				adminApi.deletestudentcourse(row.id).then((res) => {
					if (res.code == 200) {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.sherchList()
					}
				})
			})
		},
		outmoeClick(row){
			this.$confirm('此操作将对该学员退费, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				adminApi.outmoneApi(row.id).then((res) => {
					if (res.code == 200) {
						this.$message({
							type: 'success',
							message: '操作成功!'
						});
						this.sherchList()
					}
				})
			})
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
			this.dialogVisible = false;
		},
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					adminApi.addstudentcourseApi(this.ruleForm).then((res) => {
						if (res.code == 200) {
							this.$message.success(res.msg);
							this.$refs[formName].resetFields();
							this.ruleForm.remarks = "";
							this.ruleForm.password = "";
							this.sherchQuer()
							this.dialogVisible = false
						}
					})
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		addcanpus() {
			this.texts = "添加购买信息";
			this.standard = 0
			this.dialogVisible = true;
		},
		okpdfs() {
			let _this = this;
			// 获取需转图片的范围元素
			let img = this.$refs["IMG"];
			// 图片高度
			var w = parseInt(window.getComputedStyle(img).width);
			// 图片宽度
			var h = parseInt(window.getComputedStyle(img).height);
			//滚轮置顶，避免留白
			window.pageYOffset = 0;

			document.documentElement.scrollTop = 0;
			document.body.scrollTop = 0;
			// 利用 html2canvas 下载 canvas
			html2canvas(img, {
				useCORS: true,//允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。

				dpi: 300, // 提升导出的文件的分辨率

				scale: 2 // 提升导出的文件的分辨率

			}).then(function (canvas) {
				//转化为本地的图片地址
				_this.imgURL = canvas.toDataURL();
				var filename = "合同订单.pdf";
				//一页pdf显示html页面生成的canvas高度;
				var pageHeight = (w / 592.28) * 841.89;
				//未生成pdf的html页面高度
				var leftHeight = h;
				//页面偏移
				var position = 0;
				//a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
				var imgWidth = 595.28;
				var imgHeight = (592.28 / w) * h;
				// new jsPDF("l", "pt", "a4"); l 表示横向导出；true表示压缩pdf，否则文件会很大
				var pdf = new jsPDF("p", "pt", "a4");
				//有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
				//当内容未超过pdf一页显示的范围，无需分页
				if (leftHeight < pageHeight) {
					pdf.addImage(_this.imgURL, "JPEG", 0, 0, imgWidth, imgHeight);
				} else {
					// 分页
					while (leftHeight > 0) {
						pdf.addImage(
							_this.imgURL,
							"JPEG",
							0,
							position,
							imgWidth,
							imgHeight
						);
						leftHeight -= pageHeight;
						position -= 841.89;
						//避免添加空白页
						if (leftHeight > 0) {
							pdf.addPage();
						}
					}
				}
				//转pdf下载
				pdf.save(filename);
				this.pdfVisible = false;
			});
		},
	},
};
</script>

<style lang="scss">
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409EFF;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
